package org.flycloud.web.url.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RestController
public class UrlController {

	private static String root = "./data/";

	@RequestMapping("/create/**")
	public void create(HttpServletRequest request, @RequestParam("name") String name, @RequestParam("url") String url,
			@RequestParam(name = "desc", defaultValue = "") String desc) throws UnsupportedEncodingException {
		String filePath = request.getRequestURI().substring("/create/".length());
		filePath = URLDecoder.decode(filePath, "UTF8");
		File dir = new File(root + filePath);
		if (!dir.exists()) {
			new File(root + filePath).mkdirs();
		}

		JSONObject obj = new JSONObject();
		obj.put("date", new Date().getTime());
		obj.put("name", name);
		obj.put("url", url);
		obj.put("desc", desc);
		writeString(dir.getAbsolutePath() + "/" + name + ".json", JSON.toJSONString(obj, true));
		return;
	}

	public static void writeString(String filePath, String content) {
		try (BufferedWriter writer = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(filePath), Charset.forName("UTF8")))) {
			writer.write(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/urls/**")
	@ResponseBody
	public JSONObject infos(HttpServletRequest request, @RequestParam(name = "query", defaultValue = "") String query,
			@RequestParam(name = "tags", defaultValue = "") String tags,
			@RequestParam(name = "page", defaultValue = "1") int currentPage,
			@RequestParam(name = "size", defaultValue = "10") int perPage) throws UnsupportedEncodingException {
		String filePath = request.getRequestURI().substring("/urls/".length());
		filePath = URLDecoder.decode(filePath, "UTF8");
		Path path = Paths.get(root + filePath);

		if (!Files.exists(path)) {
			new File(root + filePath).mkdirs();
		}

		// 加载所有的url
		JSONArray result = JsonFileProcessor.load(root + filePath);

		// 根据查询条件查询符合条件的url
		if (!query.equals("")) {
			result = search(result, query);
		}

		JSONObject obj = new JSONObject();
		obj.put("currentPage", currentPage);
		obj.put("perPage", perPage);
		obj.put("total", result.size());

		JSONArray urls = new JSONArray();
		for (int i = (currentPage - 1) * perPage; i < currentPage * perPage && i < result.size(); i++) {
			JSONObject item = result.getJSONObject(i);
			urls.add(item);
		}
		obj.put("urls", urls);

		return obj;
	}

	private JSONArray search(JSONArray result, String query) {
		JSONArray ret = new JSONArray();
		for (int i = 0; i < result.size(); i++) {
			JSONObject item = result.getJSONObject(i);
			if (item.getString("name").contains(query) || item.getString("desc").contains(query)) {
				ret.add(item);
			}
		}
		return ret;
	}
}
